import {
  type ActionType,
  ModalForm,
  type ProColumns,
  ProTable
} from '@ant-design/pro-components';
import {Button, Descriptions, message, Tag} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { approvalTransfer, getTransferDetailsById, listTransferOrderVoByPage } from '@/services/transfer/api';

type TransferFormProps = {
  open: boolean;
  onCancel: () => void;
  transferId: string;
}

const TransferForm: React.FC<TransferFormProps> = (props) => {
  const [data, setData] = useState<TransferOrderDetailsVo>({});

  const loadData = async () => {
    if (props.transferId.length <= 0) {
      return;
    }
    const res = await getTransferDetailsById({ id: props.transferId });
    if (res.code !== 0) {
      message.error('调拨单加载失败' + res.message);
      return;
    }
    setData(res?.data || {});
  }

  const handleApproval = async () => {
    const res = await approvalTransfer(props.transferId );
    if (res.code !== 0 || res.data == false) {
      message.error('调拨单审批失败' + res.message);
      return;
    }
    message.success('调拨单审批成功');
    props.onCancel();
  }

  useEffect(() => {
    loadData();
  }, [props.transferId]);

  return (
    <ModalForm<TransferOrderDetailsVo>
      layout="vertical"
      open={props.open}
      onFinish={async () => {
        await handleApproval();
      }}
      submitter={{
        searchConfig: {
          submitText: '审批',
        },
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={{
        destroyOnClose: true,
        onCancel: props.onCancel,
      }}
    >
      <Descriptions title="调拨单明细 " bordered>
        <Descriptions.Item label="调拨单号">{data.transferNo}</Descriptions.Item>
        <Descriptions.Item label="源仓库名称">{data.originWarehouseName}</Descriptions.Item>
        <Descriptions.Item label="源仓库代码">{data.originWarehouseCode}</Descriptions.Item>
        <Descriptions.Item label="目标仓库名称">{data.targetWarehouseName}</Descriptions.Item>
        <Descriptions.Item label="目标仓库代码">{data.targetWarehouseCode}</Descriptions.Item>
        {data?.details?.map((item, index) => (
          <>
            <Descriptions.Item label="货品代码">{item.goodsCode}</Descriptions.Item>
            <Descriptions.Item label="名称">{item.goodsName}</Descriptions.Item>
            <Descriptions.Item label="数量">{item.quantity}</Descriptions.Item>
          </>
        ))}
      </Descriptions>
    </ModalForm>
  );
};

const TransferApproval: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [transferId, setTransferId] = useState<string>('');
  const [isOperate, setIsOperate] = useState<boolean>(false);
  const [data, setData] = useState<TransferOrderVo[]>([]);
  const [total, setTotal] = useState<number>(0);

  const columns: ProColumns<TransferOrderVo>[] = [
    {
      title: '源仓库名称',
      width: 120,
      dataIndex: 'originWarehouseName',
    },
    {
      title: '目标仓库名称',
      width: 120,
      dataIndex: 'targetWarehouseName',
    },
    {
      title: '调拨单号',
      width: 120,
      dataIndex: 'transferNo',
    },
    {
      title: '状态',
      width: 120,
      hideInSearch: true,
      render: (text, record) => {
        if (record.status===90) {
          return <Tag color="#2db7f5">完成</Tag>;
        } else {
          return <Tag color="yellow">作业中</Tag>;
        }
      },
      dataIndex: 'status',
    },
    {
      title: '创建时间',
      width: 120,
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      key: 'option',
      render: (text, record, _, action) => [
        <Button
          key="edit"
          onClick={() => {
            setIsOperate(true);
            setTransferId(record?.id || '');
          }}
          type="primary"
        >
          详情
        </Button>,
      ],
    },
  ];

  const loadData = async (params: any) => {
    const res = await listTransferOrderVoByPage({
      params: {
        ...params,
      },
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code !== 0) {
      message.error('调拨单数据加载失败 ' + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
  }

  useEffect(() => {
    loadData({});
  }, [currentPage]);

  return (
    <>
      <ProTable<TransferOrderVo>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={data}
        request={async (params) => {
          await loadData(params);
          return data;
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => setCurrentPage(page),
          total: total,
        }}
        headerTitle="调拨单"
        toolBarRender={() => []}
      />
      <TransferForm open={isOperate} onCancel={() => setIsOperate(false)} transferId={transferId} />
    </>
  );
};

export default TransferApproval;
